import os
from os import path

from flask import Flask

from . import Response
from .config import Config
from .db import db
from .ext import init_ext

app = Flask(__name__)
app.config.from_object(Config())
init_ext(app)


@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Methods'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


@app.before_first_request
def create_assets():
    if not path.exists(os.environ['ASSETS_PATH']):
        os.mkdir(os.environ['ASSETS_PATH'])

    # init db
    db_file_path = path.join(path.dirname(path.abspath(__file__)), r'..\rpa.db')
    if not path.exists(db_file_path):
        db.create_all()


@app.errorhandler(Exception)
def handle_invalid_usage(error):
    return Response.error(error)
